package com.fesnakj.todos.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.fesnakj.todos.model.User;
import com.fesnakj.todos.repository.UserRepository;

@Repository
@Transactional
public class JpaUserDao implements UserRepository {

    @PersistenceContext
    private EntityManager em;

    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    public User save(User user) {
        em.persist(user);
        logger.info("User " + user + " persisted.");
        return user;
    }

    @Override
    public User find(User user) {
        return em.find(User.class, user.getId());

    }

    @Override
    public User findById(int id) {
       return em.find(User.class, id);

    }

    @Override
    public List<User> findAll() {
        TypedQuery<User> query = em.createNamedQuery("User.findAll", User.class);
        List<User> users = query.getResultList();
        return users;
    }

    @Override
    public void delete(User user) {
        User removable = em.find(User.class, user.getId());
        em.remove(removable);
    }

    @Override
    public void deleteById(int id) {
        User removable = em.find(User.class, id);
        em.remove(removable);
    }

    @Override
    public long countAll() {
        return findAll().size();
    }


}